package com.example.service.impl;

import com.example.entity.Article;
import com.example.mapper.ArticleMapper;
import com.example.mapper.CategoryMapper;
import com.example.mapper.TagMapper;
import com.example.service.PopularService;
import com.example.vo.CategoryPopularVO;
import com.example.vo.TagPopularVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 热门内容服务实现类
 */
@Slf4j
@Service
public class PopularServiceImpl implements PopularService {
    
    @Resource
    private ArticleMapper articleMapper;
    
    @Resource
    private TagMapper tagMapper;
    
    @Resource
    private CategoryMapper categoryMapper;
    
    /**
     * 获取热门文章
     * @param sortBy 排序方式: favorites(收藏数), likes(点赞数), comments(评论数)
     * @return 热门文章列表
     */
    @Override
    public List<Article> getPopularArticles(String sortBy) {
        log.info("获取热门文章，排序方式: {}", sortBy);
        
        List<Article> articles;
        
        switch (sortBy) {
            case "likes":
                articles = articleMapper.getPopularArticlesByLikes();
                break;
            case "comments":
                articles = articleMapper.getPopularArticlesByComments();
                break;
            case "favorites":
            default:
                articles = articleMapper.getPopularArticlesByFavorites();
                break;
        }
        
        // 处理文章内容，如去除HTML标签、处理摘要等
        for (Article article : articles) {
            processArticleContent(article);
        }
        
        return articles;
    }
    
    /**
     * 获取热门标签
     * @return 热门标签列表
     */
    @Override
    public List<TagPopularVO> getPopularTags() {
        log.info("获取热门标签");
        return tagMapper.findPopularTags(15);
    }
    
    /**
     * 获取热门分类
     * @return 热门分类列表
     */
    @Override
    public List<CategoryPopularVO> getPopularCategories() {
        log.info("获取热门分类");
        return categoryMapper.findPopularCategories(10);
    }
    
    /**
     * 处理文章内容，提取摘要等操作
     * @param article 文章对象
     */
    private void processArticleContent(Article article) {
        if (article == null) {
            return;
        }
        
        // 如果文章没有摘要，则从内容中提取
        if (article.getDescription() == null || article.getDescription().isEmpty()) {
            String content = article.getContent();
            if (content != null) {
                // 去除HTML标签
                content = content.replaceAll("<[^>]+>", "");
                // 提取摘要
                if (content.length() > 150) {
                    article.setDescription(content.substring(0, 150) + "...");
                } else {
                    article.setDescription(content);
                }
            }
        }
    }
} 